<?php

namespace app\proxy\controller\page;

use app\common\enum\settings\SettingEnum;
use app\proxy\controller\Controller;
use app\proxy\model\page\Page as PageModel;
use app\proxy\model\page\PageCategory as PageCategoryModel;
use app\proxy\model\proxy\Region;
use app\shop\model\settings\Setting as SettingModel;
use app\proxy\model\proxy\User as ProxyUser;

/**
 * App页面管理
 */
class Page extends Controller
{


    public function getRegions($activeName='', $page_type = 10)
    {
        $regions = (new Region())->where("is_delete", '=', 0)
            ->where("proxy_id", '=', $this->getProxyId())
            ->where("level", '<', 3)
            ->field(['province_id', 'city_id', 'region_id', 'level'])
            ->select()->toArray();
        $model = new PageModel;
        foreach ($regions as &$region) {
            $region["region_name"] = \app\common\model\region\Region::getMergerName($region["region_id"]);
            $region["pageNum"] = $model->where([
                'is_delete' => 0,
                'page_type' => $page_type,
                "proxy_id" => $this->getProxyId(),
                "province_id" => $region["province_id"],
                "city_id" => $region["city_id"],
            ])->count();
        }
        if (empty($activeName) && !empty($regions)) {
            $activeName = $regions[0]["region_id"];
        }
        return $this->renderSuccess('', compact('activeName', 'regions'));
    }

    public function copyPage($level, $fromId, $regionId, $page_type)
    {
        if (empty($regionId)) {
            return $this->renderError('请选择目标地区');
        }
        $region = (new Region())->where("is_delete", '=', 0)
            ->where("proxy_id", '=', $this->getProxyId())
            ->where("level", '<', 3)
            ->where("region_id", '=', $regionId)
            ->field(['province_id', 'city_id', 'region_id', 'level'])
            ->find();
        if (empty($region)) {
            return $this->renderError('目标地区不可用');
        }
        $nosh = false;
        $proxyUser = ProxyUser::detail($this->getProxyId());
        if($proxyUser&&isset($proxyUser['authority'])){
            $authority = json_decode($proxyUser['authority'],true);
            if(isset($authority['page'])&&$authority['page']==1){
                $nosh = true;
            }
        }
        $model = new PageModel;
        $page_name = "";
        if ($level == -1 && $fromId > 0) {
            $fromPage = $model->find($fromId);
            $page_name = '复制自-' . $fromId;
        } elseif ($level == 0) {
            $fromPage = $model->where(['is_delete' => 0, 'page_type' => $page_type, "proxy_id" => 0, "province_id" => 0, "city_id" => 0])
                ->order("is_default", "desc")
                ->find();
            $page_name = '复制自-平台页面';
        } elseif ($level == 1) {
            $fromPage = $model->where(['is_delete' => 0, 'page_type' => $page_type, "province_id" => $region["province_id"], "city_id" => 0, 'is_default' => 1, 'is_audit' => 1])
                ->find();
            $page_name = '复制自-省代理页面';
        }
        if (empty($fromPage)) {
            return $this->renderError('源页面不存在');
        }
        $data = [
            'page_type' => $fromPage['page_type'],
            'page_name' => $page_name,
            'page_data' => $fromPage["page_data"],
            'is_default' => 0,
            'app_id' => $model::$app_id,
            'is_delete' => 0,
            'province_id' => $region["province_id"],
            'city_id' => $region["city_id"],
            'proxy_id' => $this->getProxyId(),
            'is_audit' => $fromPage['is_audit'],
        ];
        if($nosh){
            $data['is_audit'] = 1;
        }
        $model->save($data);
        return $this->renderSuccess('复制成功');
    }

    /**
     * 页面列表
     */
    public function list()
    {
        $model = new PageModel;
        $list = $model->getList($this->postData(), 10, $this->getRegionIds(), $this->getProxyId());
        //查找默认
        $default = $model::getHomeDefault($this->postData()["region_id"],$this->getProxyId());
        return $this->renderSuccess('', compact('list', 'default'));
    }

    /**
     * 页面列表
     */
    public function index()
    {
        $model = new PageModel;
        $list = $model->getList($this->postData(), 20, $this->getRegionIds(), $this->getProxyId());
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 新增页面
     */
    public function add()
    {
        $model = new PageModel;
        if ($this->request->isGet()) {
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => ['page' => $model->getDefaultPage(), 'items' => []],
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }
        // 接收post数据
        $post = $this->postData();
        if (!$model->add(json_decode($post['params'], true), 20, $this->getProxyId(), $post["region_id"])) {
            return $this->renderError($model->getError() ?: '添加失败');
        }
        return $this->renderSuccess('添加成功');
    }

    /**
     * 首页编辑
     * @return \think\response\Json
     */
    public function home()
    {
        return $this->edit();
    }

    /**
     * 编辑页面
     */
    public function edit($page_id = null)
    {
        $model = $page_id > 0 ? PageModel::detail($page_id) : PageModel::getHomePage();
        if ($this->request->isGet()) {
            $jsonData = $model['page_data'];
            jsonRecursive($jsonData);
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => $jsonData,
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }

        // 接收post数据
        $post = $this->postData();
        if (!$model->edit(json_decode($post['params'], true),$this->getProxyId())) {
            return $this->renderError($model->getError() ?: '更新失败');
        }
        return $this->renderSuccess('更新成功');
    }

    /**
     * 删除页面
     */
    public function delete($page_id)
    {
        // 帮助详情
        $model = PageModel::detail($page_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function categoryList()
    {

        $regions = (new Region())->where("is_delete", '=', 0)
            ->where("proxy_id", '=', $this->getProxyId())
            ->where("level", '<', 3)
            ->field(['province_id', 'city_id', 'region_id', 'level'])
            ->select();
//        return $this->renderSuccess('', compact('regions'));

        $list = [];
        $model = new PageCategoryModel;
        $where = ["proxy_id" => 0, "province_id" => 0, "city_id" => 0];
        $default = $model->where($where)->find();
        foreach ($regions as $region) {
            $where = ["proxy_id" => $this->getProxyId(), "province_id" => $region["province_id"], "city_id" => $region["city_id"]];
            $category = $model->where($where)->find();
            if (empty($category) && $region["city_id"] > 0) {
                $where = ["province_id" => $region["province_id"], "city_id" => 0];
                $category = $model->where($where)->find();
            }
            if (empty($category)) {
                $category = clone $default;
            }
            $category["region_id"] = $region["region_id"];
            $category["region_name"] = \app\common\model\region\Region::getMergerName($region["region_id"]);
            $list[] = $category;
        }
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 分类模板
     */
    public function category()
    {
        $post = $this->postData();

        $region = (new Region())->where("is_delete", '=', 0)
            ->where("proxy_id", '=', $this->getProxyId())
            ->where("level", '<', 3)
            ->where("region_id", $post["region_id"])
            ->field(['province_id', 'city_id', 'region_id', 'level'])
            ->find();

        if (empty($region)) {
            return $this->renderError('您无权操作此地区');
        }
        $where = ["proxy_id" => $this->getProxyId(), "province_id" => $region["province_id"], "city_id" => $region["city_id"]];
        $model = new PageCategoryModel;
        $category = $model->where($where)->find();
        $data["share_title"] = $post["share_title"];
        $data["category_style"] = $post["category_style"];
        if ($category) {
            $category->save($data);
        } else {
            $data["proxy_id"] = $this->getProxyId();
            $data["province_id"] = $region["province_id"];
            $data["city_id"] = $region["city_id"];
            $data["is_audit"] = 1;
            $data["app_id"] = $model::$app_id;
            $model->newQuery()->save($data);
        }

        return $this->renderSuccess('更新成功', $model->getLastSql());
    }

    /**
     * 新增页面
     */
    public function addPage()
    {
        $model = new PageModel;
        if ($this->request->isGet()) {
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => ['page' => $model->getDefaultPage(), 'items' => []],
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }
        // 接收post数据
        $post = $this->postData();
        if (!$model->add(json_decode($post['params'], true), 10, $this->getProxyId(), $post["region_id"])) {
            return $this->renderError($model->getError() ?: '添加失败');
        }
        return $this->renderSuccess('添加成功');
    }

    /**
     * 编辑页面
     */
    public function editPage($page_id)
    {
        $model = PageModel::detail($page_id);
        if ($this->request->isGet()) {
            $jsonData = $model['page_data'];
            jsonRecursive($jsonData);
            return $this->renderSuccess('', [
                'defaultData' => $model->getDefaultItems(),
                'jsonData' => $jsonData,
                'opts' => [
                    'catgory' => [],
                ]
            ]);
        }
        // 接收post数据
        $post = $this->postData();
        if (!$model->edit(json_decode($post['params'], true),$this->getProxyId())) {
            return $this->renderError($model->getError() ?: '更新失败');
        }
        return $this->renderSuccess('更新成功');
    }

    /**
     * 删除页面
     */
    public function deletePage($page_id)
    {
        // 详情
        $model = PageModel::detail($page_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 设置默认
     */
    public function setPage($page_id)
    {
        // 页面详情
        $model = PageModel::detail($page_id);
        if (!$model->setDefault()) {
            return $this->renderError($model->getError() ?: '设置失败');
        }
        return $this->renderSuccess('设置成功');
    }

    /**
     * 商城设置
     */
    public function nav()
    {
        if ($this->request->isGet()) {
            $data = SettingModel::getItem('nav');
            return $this->renderSuccess('', compact('data'));
        }
        $model = new SettingModel;
        $data = $this->postData();
        if ($model->edit('nav', $data)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 底部菜单
     */
    public function bottomnav()
    {
        $vars = SettingModel::getItem(SettingEnum::NAV);
        return $this->renderSuccess('', compact('vars'));
    }

    /**
     * 底部菜单设置
     */
    public function bottomedit()
    {
        $model = new SettingModel;
        $data = $this->postData();
        if ($model->edit('nav', $data)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }
}
